package cn.owng.server.plaza.socket;

import cn.owng.protobuf.plaza.Message;
import cn.owng.server.common.support.ContextProvider;
import com.google.protobuf.util.JsonFormat;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.BinaryWebSocketHandler;

import java.util.Map;

/**
 * 微信公众号请关注: 开源螺丝钉
 * <br>
 * 码云请关注: <a href="https://gitee.com/xiyoufang">https://gitee.com/xiyoufang</a>
 * <br>
 * 哔哩哔哩请关注: <a href="https://space.bilibili.com/438927834">https://space.bilibili.com/438927834</a>
 *
 * @author xiyoufang
 */
@Slf4j
@Component
public class PlazaWebSocketHandler extends BinaryWebSocketHandler {

    /**
     * 处理二进制消息
     *
     * @param session WebSocketSession
     * @param message BinaryMessage
     * @throws Exception 异常
     */
    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
        byte[] payload = message.getPayload().array();
        log.info("接收到消息, 长度:{}", payload.length);
        Message.Request request = Message.Request.parseFrom(payload);
        log.info("接收到的Protobuf: {}", JsonFormat.printer().includingDefaultValueFields().print(request));
        Map<String, RequestHandler> handlers = ContextProvider.context().getBeansOfType(RequestHandler.class);
        for (Map.Entry<String, RequestHandler> entry : handlers.entrySet()) {
            RequestHandler handler = entry.getValue();
            if (handler.isSupport(session, request)) {
                handler.handle(session, request);
            }
        }
    }
}
